package com.panda.pandawash.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.panda.pandawash.util.ProductsListUtils;
import com.panda.pandawash.R;
import com.panda.pandawash.adapter.AdapterPopWindowList;
import com.panda.pandawash.application.CDApplication;
import com.panda.pandawash.util.PermissionUtils;
import com.panda.pandawash.view.StatusBarCompat;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

@ContentView(R.layout.activity_person_info_setting)
public class PersonInfoSettingActivity extends AppCompatActivity {

    private String TAG = "PersonInfoSettingAct";

    private PopupWindow setPortraitWindow;

    public static final int CUT_PICTURE_FROM_ALBUM = 1;
    public static final int CUT_PICTURE_FROM_CAMERA = 2;
    public static final int SHOW_PICTURE = 3;
    private String quiturlString = "http://yslink.xyz/motor_th/index.php/Home/User/Mlogout";

    @ViewInject(R.id.modify_head_layout)
    private LinearLayout setPortraitLayout;

    @ViewInject(R.id.my_portrait)
    private ImageView myPortraiImage;

    @ViewInject(R.id.modify_passwd_layout)
    private LinearLayout modifyPasswordLayout;

    @ViewInject(R.id.account_content)
    private TextView mAcountName;

    private Uri imageUri;
    private File outputImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.KITKAT) {
            StatusBarCompat.compat(this, getResources().getColor(R.color.colorPrimary));
        }
        outputImage = new File(Environment.getExternalStorageDirectory(), "temp.png");

        setPortraitLayout.setOnClickListener(mClickListener);
        modifyPasswordLayout.setOnClickListener(mClickListener);

        Bitmap bm = loadImageFromFile(this);
        if (bm != null) {
            myPortraiImage.setImageBitmap(bm);
        } else {
            //如果SD里面没有则需要从服务器取头像，取回来的头像再保存在SD中
        }
        mAcountName.setText(CDApplication.getIntance().getUserInfo().getUseraccount().toString());

    }

    private View.OnClickListener mClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generamethod stub
            switch (v.getId()) {
                case R.id.modify_head_layout:
                    // check loction permission
                    if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M) {
                        if (!PermissionUtils.storagePermission) {
                            PermissionUtils.storageCheck(PersonInfoSettingActivity.this);
                        }
                    }
                    showProductsList(v);
                    break;
                case R.id.modify_passwd_layout:
                    //Toast.makeText(PersonInfoSettingActivity.this, "修改密码", Toast.LENGTH_SHORT).show();
                    Intent modifyPassword = new Intent(PersonInfoSettingActivity.this, ModifyPSDActivity.class);
                    startActivity(modifyPassword);
                    break;
                default:
                    break;
            }

        }
    };

    @Event(R.id.btn_personInfo_return)
    private void excuteReturn(View v) {
        finish();
    }

    private void showProductsList(View v) {
        Log.d("gwf_add", "enter showProductsList");
        if (setPortraitWindow == null) {

            LayoutInflater myInflater = LayoutInflater.from(this);
            View myView = myInflater.inflate(R.layout.popwindow_set_portrait, null);
            setPortraitWindow = new PopupWindow(myView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            TextView setFromCamera = (TextView) myView.findViewById(R.id.set_from_camera);
            TextView setFromAlbum = (TextView) myView.findViewById(R.id.set_from_album);
            TextView cancelSelect = (TextView) myView.findViewById(R.id.cancel_select);

            setFromCamera.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    chooseByCamera(v);
                }
            });

            setFromAlbum.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    chooseByGallery(v);
                }
            });

            cancelSelect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    setPortraitWindow.dismiss();
                    //setPortraitButton.setClickable(true);
                }
            });

            ProductsListUtils productsListUtils = new ProductsListUtils(this);
            AdapterPopWindowList myAdapterPopWindowList = new AdapterPopWindowList(productsListUtils.getProductsList(), this);

        }

        setPortraitWindow.setBackgroundDrawable(new BitmapDrawable());
        setPortraitWindow.setFocusable(true);
        setPortraitWindow.update();
        setPortraitWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
    }

    /// 设置头像 2017年3月14日17:28:15

    private static final String PHOTO_FILE_NAME = "personPhoto.png";

    public static void saveImageToFile(Context ctx, Bitmap bitmap) {
        FileOutputStream fos = null;
        try {
            fos = ctx.openFileOutput(PHOTO_FILE_NAME, Context.MODE_PRIVATE);
            Log.d("gwf_add", "fos = " + fos);
            boolean compress = bitmap.compress(Bitmap.CompressFormat.PNG, 80, fos);
            Log.d("gwf_add", "bitmap.compress = " + compress);
            bitmap.compress(Bitmap.CompressFormat.PNG, 80, fos);
        } catch (Exception e) {
            Toast.makeText(ctx, "failed to save Image", Toast.LENGTH_SHORT).show();
        }finally{
            try {
                if(null != fos){
                    fos.close();
                }
            }catch (Exception e) {
            }
        }
    }

    public static Bitmap loadImageFromFile(Context ctx) {
        FileInputStream fos = null;
        Bitmap bitmap = null;
        try {
            fos = ctx.openFileInput(PHOTO_FILE_NAME);
            bitmap = BitmapFactory.decodeStream(fos);
        } catch (Exception e) {
            //Toast.makeText(this, "failed", Toast.LENGTH_SHORT).show();
        }finally{
            try {
                if(null != fos){
                    fos.close();
                }
            }catch (Exception e) {
            }
        }

        return bitmap;
    }
    void chooseByGallery(View v){

        Toast.makeText(PersonInfoSettingActivity.this, "setFromAlbum", Toast.LENGTH_LONG).show();
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        imageUri = Uri.fromFile(outputImage);
        Log.i("bear_", "GrallyPATH = " + imageUri);
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        // 此处调用了图片选择器
        // 如果直接写intent.setDataAndType("image/*");
        // 调用的是系统图库
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, CUT_PICTURE_FROM_ALBUM);
    }

    void chooseByCamera(View view){
        // TODO Auto-generated method stub
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 将File对象转换成Uri对象
        // Uri表标识着图片的地址

        imageUri = Uri.fromFile(outputImage);
        Log.i("gwf_add", "PhotoPATH = " + imageUri);
        // 隐式调用照相机程序
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 拍下的照片会被输出到output_image.jpg中去
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        // 此处是使用的startActivityForResult（）
        // 因此在拍照完后会有结果返回到onActivityResult（）中去，返回值即为CUT_PICTURE
        // onActivityResult（）中主要是实现图片裁剪
        startActivityForResult(intent, CUT_PICTURE_FROM_CAMERA);
    }



    private void cropImageUriFromCamera(Uri uri, int outputX, int outputY, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
    }

    private void cropImageUriFromAlbum(Uri uri1, Uri uri2, int outputX, int outputY, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri1, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case CUT_PICTURE_FROM_ALBUM:
                if (resultCode == RESULT_OK) {
                    cropImageUriFromAlbum(data.getData(), imageUri, 115, 115, SHOW_PICTURE);
                }
                break;

            case CUT_PICTURE_FROM_CAMERA:
                if (resultCode == RESULT_OK) {
                    cropImageUriFromCamera(imageUri, 115, 115, SHOW_PICTURE);
                }
                break;
            case SHOW_PICTURE:
                if (resultCode == RESULT_OK) {
                    try {
                        // 将output_image.jpg对象解析成Bitmap对象，然后设置到ImageView中显示出来
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        myPortraiImage.setImageBitmap(bitmap);

                        saveImageToFile(this, bitmap);

                        if (setPortraitWindow != null) {
                            setPortraitWindow.dismiss();
                        }
                        Log.d("gwf_add", "crop pic success");
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                    outputImage.delete();
                }
                break;
            default:
                break;
        }
    }
    /// 设置头像 2017年3月14日17:28:23

}
